/**
 * Product Compare Functions
 * 产品比较功能脚本
 * 
 * @package WP Bootstrap Woo
 */

(function($) {
    'use strict';

    const ProductCompare = {
        compareList: [],
        maxItems: 4,

        init: function() {
            this.loadCompareList();
            this.bindEvents();
            this.updateCompareCount();
        },

        // 加载比较列表
        loadCompareList: function() {
            const cookie = this.getCookie('wbw_compare');
            if (cookie) {
                try {
                    this.compareList = JSON.parse(cookie);
                } catch (e) {
                    this.compareList = [];
                }
            }
        },

        // 绑定事件
        bindEvents: function() {
            // 添加到比较列表
            $(document).on('click', '.btn-compare', this.addToCompare.bind(this));
            
            // 移除比较项
            $(document).on('click', '.remove-compare-item', this.removeFromCompare.bind(this));
            
            // 清空比较列表
            $(document).on('click', '.clear-compare', this.clearCompare.bind(this));
            
            // 查看比较页面
            $(document).on('click', '.view-compare', this.viewCompare.bind(this));
            
            // 比较浮动窗口
            this.createCompareWidget();
        },

        // 添加到比较列表
        addToCompare: function(e) {
            e.preventDefault();
            
            const $button = $(e.currentTarget);
            const productId = $button.data('product-id');
            
            if (this.compareList.length >= this.maxItems) {
                this.showNotification('You can compare maximum ' + this.maxItems + ' products', 'warning');
                return;
            }

            if (this.compareList.includes(productId)) {
                this.showNotification('Product already in compare list', 'info');
                return;
            }

            $button.addClass('loading');
            
            // Ajax请求
            $.ajax({
                url: wbw_ajax.ajax_url,
                type: 'POST',
                data: {
                    action: 'wbw_add_to_compare',
                    product_id: productId,
                    nonce: wbw_ajax.nonce
                },
                success: (response) => {
                    if (response.success) {
                        this.compareList.push(productId);
                        this.saveCompareList();
                        this.updateCompareCount();
                        this.updateCompareWidget();
                        this.showNotification('Added to compare list', 'success');
                        $button.addClass('in-compare');
                    } else {
                        this.showNotification(response.data.message, 'error');
                    }
                    $button.removeClass('loading');
                },
                error: () => {
                    this.showNotification('Something went wrong', 'error');
                    $button.removeClass('loading');
                }
            });
        },

        // 从比较列表移除
        removeFromCompare: function(e) {
            e.preventDefault();
            
            const productId = parseInt($(e.currentTarget).data('product-id'));
            const index = this.compareList.indexOf(productId);
            
            if (index > -1) {
                this.compareList.splice(index, 1);
                this.saveCompareList();
                this.updateCompareCount();
                this.updateCompareWidget();
                
                // 移除DOM元素
                $(e.currentTarget).closest('.compare-item').fadeOut(() => {
                    $(this).remove();
                });
                
                // 更新按钮状态
                $(`.btn-compare[data-product-id="${productId}"]`).removeClass('in-compare');
                
                this.showNotification('Removed from compare list', 'info');
            }
        },

        // 清空比较列表
        clearCompare: function(e) {
            e.preventDefault();
            
            if (confirm('Are you sure you want to clear all compare items?')) {
                this.compareList = [];
                this.saveCompareList();
                this.updateCompareCount();
                this.updateCompareWidget();
                
                // 重置所有按钮状态
                $('.btn-compare').removeClass('in-compare');
                
                this.showNotification('Compare list cleared', 'info');
            }
        },

        // 查看比较页面
        viewCompare: function(e) {
            e.preventDefault();
            
            if (this.compareList.length < 2) {
                this.showNotification('Please add at least 2 products to compare', 'warning');
                return;
            }
            
            // 构建比较页面URL
            const compareUrl = wbw_ajax.site_url + '/compare/?products=' + this.compareList.join(',');
            window.location.href = compareUrl;
        },

        // 创建比较浮动组件
        createCompareWidget: function() {
            if ($('#compare-widget').length) return;
            
            const widgetHtml = `
                <div id="compare-widget" class="compare-widget">
                    <div class="widget-header">
                        <span class="widget-title">Compare (<span class="compare-count">0</span>)</span>
                        <button type="button" class="widget-toggle">
                            <i class="feather-chevron-up"></i>
                        </button>
                    </div>
                    <div class="widget-content">
                        <div class="compare-items"></div>
                        <div class="widget-actions">
                            <button type="button" class="btn-compare-action view-compare">Compare</button>
                            <button type="button" class="btn-compare-action clear-compare">Clear</button>
                        </div>
                    </div>
                </div>
            `;
            
            $('body').append(widgetHtml);
            
            // 折叠/展开功能
            $(document).on('click', '.widget-toggle', function() {
                const $widget = $('#compare-widget');
                const $content = $widget.find('.widget-content');
                const $icon = $(this).find('i');
                
                if ($content.is(':visible')) {
                    $content.slideUp();
                    $icon.removeClass('feather-chevron-up').addClass('feather-chevron-down');
                } else {
                    $content.slideDown();
                    $icon.removeClass('feather-chevron-down').addClass('feather-chevron-up');
                }
            });
        },

        // 更新比较组件
        updateCompareWidget: function() {
            const $widget = $('#compare-widget');
            const $items = $widget.find('.compare-items');
            
            if (this.compareList.length === 0) {
                $widget.removeClass('has-items');
                $items.empty();
                return;
            }
            
            $widget.addClass('has-items');
            
            // 获取产品信息并更新组件
            this.getCompareProducts().then(products => {
                let itemsHtml = '';
                products.forEach(product => {
                    itemsHtml += `
                        <div class="compare-item" data-product-id="${product.id}">
                            <div class="item-image">
                                <img src="${product.image}" alt="${product.name}">
                            </div>
                            <div class="item-info">
                                <h6>${product.name}</h6>
                                <span class="price">${product.price}</span>
                            </div>
                            <button type="button" class="remove-compare-item" data-product-id="${product.id}">
                                <i class="feather-x"></i>
                            </button>
                        </div>
                    `;
                });
                $items.html(itemsHtml);
            });
        },

        // 获取比较产品信息
        getCompareProducts: function() {
            if (this.compareList.length === 0) {
                return Promise.resolve([]);
            }
            
            return new Promise((resolve) => {
                $.ajax({
                    url: wbw_ajax.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'wbw_get_compare_products',
                        product_ids: this.compareList,
                        nonce: wbw_ajax.nonce
                    },
                    success: (response) => {
                        if (response.success) {
                            resolve(response.data);
                        } else {
                            resolve([]);
                        }
                    },
                    error: () => resolve([])
                });
            });
        },

        // 更新比较计数
        updateCompareCount: function() {
            const count = this.compareList.length;
            $('.compare-count').text(count);
            
            // 更新按钮状态
            this.compareList.forEach(productId => {
                $(`.btn-compare[data-product-id="${productId}"]`).addClass('in-compare');
            });
        },

        // 保存比较列表到Cookie
        saveCompareList: function() {
            this.setCookie('wbw_compare', JSON.stringify(this.compareList), 30);
        },

        // 获取Cookie
        getCookie: function(name) {
            const value = `; ${document.cookie}`;
            const parts = value.split(`; ${name}=`);
            if (parts.length === 2) return parts.pop().split(';').shift();
        },

        // 设置Cookie
        setCookie: function(name, value, days) {
            const expires = new Date(Date.now() + days * 864e5).toUTCString();
            document.cookie = `${name}=${encodeURIComponent(value)}; expires=${expires}; path=/`;
        },

        // 显示通知
        showNotification: function(message, type = 'info') {
            // 复用WooCommerce模块的通知系统
            if (window.WBW_WooCommerce) {
                window.WBW_WooCommerce.showNotification(message, type);
            } else {
                alert(message);
            }
        }
    };

    // 初始化
    $(document).ready(function() {
        ProductCompare.init();
    });

    // 全局暴露
    window.ProductCompare = ProductCompare;

})(jQuery);